package com.kevin.server;

import com.kevin.Entity.MessageRecord;
import com.kevin.Entity.OptCode;
import com.kevin.serial.MessageRecordEncoder;
import com.kevin.serial.MessageRecorderDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class NettyProtocalServer {

    public static void main(String[] args) {

        ServerBootstrap server = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup(2);
        EventLoopGroup worker = new NioEventLoopGroup(4);
        server.group(boss,worker);
        server.channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                                Integer.MAX_VALUE,
                                9,
                                4,0,0))
                                .addLast(new MessageRecordEncoder())
                                .addLast(new MessageRecorderDecoder())
                                .addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        MessageRecord messageRecord = (MessageRecord)msg;
                                        System.out.println("服务端收到消息："+messageRecord.toString());
                                        messageRecord.getHeader().setOptCode(OptCode.OPT_RES.getCode());
                                        messageRecord.setBody("server recieve message");
                                        ctx.writeAndFlush(messageRecord);


                                    }
                                });
                    }
                });

        try {
            ChannelFuture channelFuture = server.bind(8080).sync();
            System.out.println("server start 8080");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }
}
